package com.rd.student.ruanjian.class4.lichunquan.Text03;

import java.util.Scanner;
import java.util.concurrent.atomic.AtomicInteger;

public class Test03 {
    public static void main(String[] args) {
        System.out.println("输入数字");
        AtomicInteger atomicInteger =
                new AtomicInteger(new Scanner(System.in).nextInt());
        System.out.println("输入自增次数");
        Add add = new Add(atomicInteger, new Scanner(System.in).nextInt());
        System.out.println("输入自减次数");
        De de = new De(atomicInteger, new Scanner(System.in).nextInt());
        new Thread(add, "自增1号").start();
        new Thread(add, "自增2号").start();
        new Thread(de, "自减1号").start();
        new Thread(de, "自减2号").start();

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //检查最后结果
        System.out.println(atomicInteger);
    }
}

class Add implements Runnable {
    AtomicInteger atomicInteger;
    volatile int count;
    public Add(AtomicInteger atomicInteger, int count) {
        this.atomicInteger = atomicInteger;
        this.count = count;
    }

    @Override
    public void run() {
        while (count > 0) {
            count--;
            synchronized (atomicInteger) {
                atomicInteger.getAndIncrement();
                System.out.println(Thread.currentThread().getName()
                        + " " + atomicInteger);
            }
        }
    }
}

class De implements Runnable {
    AtomicInteger atomicInteger;
    volatile int count;
    public De(AtomicInteger atomicInteger, int count) {
        this.atomicInteger = atomicInteger;
        this.count = count;
    }

    @Override
    public void run() {
        while (count > 0) {
            count--;
            synchronized (atomicInteger) {
                atomicInteger.getAndDecrement();
                System.out.println(Thread.currentThread().getName()
                        + " " + atomicInteger);
            }

        }
    }
}